var signJs = require("./song_sign")
var song_list = []
var innerAudioContext = wx.getBackgroundAudioManager()
Page({
  data: {
    play: false
  },
  // 输入值
  bindinput(e) {
    this.name = e.detail.value
  },
  // 点击“搜索”
  search() {
    if (!this.name || this.name == '') {
      wx.showToast({
        title: '请输入歌手或歌曲名！',
        icon: 'none'
      })
      return
    }
    this.p = 1
    this.n = 20
    song_list = []
    this.get_songs()
  },
  // 获取歌曲信息并返回
  get_songs() {
    wx.showLoading()
    let that = this
    let url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp'
    // let url = 'http://localhost:8081/query/songList'
    wx.request({
      url: url,
      data: {
        "p": that.p,
        "n": that.n,
        "w": that.name,
        "format": "json"
      },
      method: 'GET',
      dataType: 'json',
      header: {
        "content-type": "application/x-javascript;charset=utf-8"
      },
      success(res) {
        console.log(res.data.data.song.list)
        for (const index in res.data.data.song.list) {
          song_list.push(res.data.data.song.list[index])
        }
        that.setData({
          song_list: song_list
        })
      },
      fail(res) {
        console.error(res)
      },
      complete() {
        wx.hideLoading()
      }
    })
  },
  // 点击歌曲列表
  async clickSong(e) {
    let index = e.currentTarget.dataset.index
    let songmid = song_list[index].songmid
    let songname = song_list[index].songname
    let singername = song_list[index].singer[0].name
    let epname = song_list[index].albumname
    console.log(index, songmid, songname, singername, epname)
    console.log("拿到songmid", songmid)
    if (this.original != songmid) {
      this.original = songmid
      this.setData({
        songmid: songmid
      })
      let url = await this.audioUrl(songmid)
      // let url = await this.getDataByUrl(songmid)
      // console.log('最终歌曲url', url.data.data)
      // url = url.data.data
      this.playStatus = true
      innerAudioContext.title = songname
      innerAudioContext.singer = singername
      innerAudioContext.epname = epname
      innerAudioContext.src = url
      this.play()
    } else {
      if (this.playStatus == true) {
        this.playStatus = false
        this.setData({
          songmid: 'songmid'
        })
        this.pause()
      } else {
        this.playStatus = true
        this.setData({
          songmid: songmid
        })
        this.play()
      }
    }
  },
  async getDataByUrl(songmid) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://localhost:8081/query/songDetail',
        data: {
          songmid
        },
        success: res => resolve(res),
        fail: error => reject(error)
      })
    })
  },
  // 获取资源url
  async audioUrl(songmid) {
    let data = await this.set_data(songmid)
    console.log("拿到set_data的返回值", data)
    let filename = await this.get_url(data).then(res => {
      return res.data.req_0.data.midurlinfo[0].purl
    })
    console.log("拿到文件名", filename)
    let url = "https://isure.stream.qqmusic.qq.com/" + filename
    return url
  },
  // 播放
  play() {
    innerAudioContext.play()
  },
  // 暂停
  pause() {
    innerAudioContext.pause()
  },
  playNone() {
    wx.showToast({
      title: '收费歌曲暂不提供播放与下载',
      icon: 'none'
    })
  },
  async set_data(songmid) {
    let data = '{"req":{"module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"358840384","calltype":0,"userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"358840384","songmid":["' + songmid + '"],"songtype":[0],"uin":"18585073516","loginflag":1,"platform":"20"}},"comm":{"uin":18585073516,"format":"json","ct":24,"cv":0}}'
    return data
  },
  async get_url(data) {
    let sign = await this.get_sign(data)
    let url = "https://u.y.qq.com/cgi-bin/musics.fcg"
    let returnUrl = await new Promise((resolve, reject) => {
      wx.request({
        url: url,
        method: "GET",
        data: {
          '-': 'getplaysongvkey38596056557178904',
          'g_tk': '1129808082',
          'sign': sign,
          'loginUin': '18585073516',
          'hostUin': '0',
          'format': 'json',
          'inCharset': 'utf8',
          'outCharset': 'utf-8',
          'notice': '0',
          'platform': 'yqq.json',
          'needNewCode': '0',
          'data': data
        },
        dataType: 'json',
        success(res) {
          resolve(res)
        },
        fail(res) {
          reject(res)
        }
      })
    })
    return returnUrl
  },
  async get_sign(data) {
    let sign = await signJs.getSecuritySign(data)
    console.log("拿到sign值并返回", sign)
    return sign
  },
  async download(e) {
    let index = e.currentTarget.dataset.index
    let songmid = song_list[index].songmid
    let url = await this.audioUrl(songmid)
    wx.showModal({
      title: "提示",
      content: "鉴于系统原因，下载的歌曲无法在本小程序以外使用。请复制下载链接后打开浏览器进行下载。",
      confirmText: "复制链接",
      success(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: url,
          })
        }
      }
    })
  },
  onLoad: function (options) {
    this.original = ''
    this.playStatus = false
  },
  onReady: function () {
    innerAudioContext.onError((res) => {
      wx.showToast({
        title: '播放资源错误，请重新尝试播放或更换曲目！',
        icon: 'none'
      })
      console.log(res)
      console.log(res.errMsg)
      console.log(res.errCode)
    })
    innerAudioContext.onEnded(() => {
      this.playStatus = false
      this.setData({
        songmid: 'songmid'
      })
      this.pause()
    })
  },
  onReachBottom: function () {
    this.p += 1
    this.get_songs()
  },
  onShareAppMessage() {
    return {
      title: "在线搜音乐",
      path: "/pages/audioTools/pages/onlineMusic/index",
      imageUrl: '/images/function_icon/online_music.png',
    }
  },
  onShareTimeline() {
    return {
      title: '在线搜音乐',
      imageUrl:'/images/function_icon/online_music.png'
    }
  },
})